from http.client import HTTPException
from typing import List
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
import json
import subprocess
from fastapi.middleware.cors import CORSMiddleware
from fastapi import FastAPI, File, UploadFile
from zhipuai import ZhipuAI

import json


from zhipuai.core import BaseModel

app = FastAPI()


class Message(BaseModel):
    role: str
    content: str


class Request(BaseModel):
    messages: List[Message]

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有来源
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有HTTP方法
    allow_headers=["*"]  # 允许所有请求头
)

key = "你的APIkey"
client = ZhipuAI(api_key=key)

app = FastAPI()


@app.post("/work/graph")
async def knowledge_graph_analysis(question: str):
    # 生成请求消息
    message_request = f" 请对以下错题进行知识图谱分析：\n{question}\n"
    message_content = '''

    你是一个专业的知识图谱分析助手，根据给定的错题，分析出与该题目有关的知识点，并以以下 JSON 格式返回：
    {
        "rootId": "N1",
        "nodes": [
        {"id": "N1", "text": "计算给定数字的阶乘并打印输出"}, {"id": "N2", "text": "阶乘定义"}, 
        {"id": "N2-1", "text": "阶乘是所有小于或等于该数的正整数的乘积"}, {"id": "N3", "text": "编程语言基础"}, 
        {"id": "N3-1", "text": "Python"}, {"id": "N4", "text": "循环结构"}, 
        {"id": "N4-1", "text": "循环结构用于实现阶乘计算的迭代过程"}, {"id": "N5", "text": "字符串操作"}, 
        {"id": "N5-1", "text": "字符串操作用于将结果以逗号分隔的形式打印"}, {"id": "N6", "text": "输入输出格式要求"},
         {"id": "N6-1", "text": "理解输入输出格式要求对于实现正确输出至关重要"}
         ],
        "lines": [
        {"from": "N1", "to": "N2"}, {"from": "N1", "to": "N3"}, 
        {"from": "N1", "to": "N4"}, {"from": "N1", "to": "N5"}, 
        {"from": "N1", "to": "N6"}, {"from": "N2", "to": "N2-1"}, 
        {"from": "N3", "to": "N3-1"}, {"from": "N4", "to": "N4-1"}, 
        {"from": "N5", "to": "N5-1"}, {"from": "N6", "to": "N6-1"}
        ]
}
    '''

    input_content = message_request + message_content
    print(f"输入内容: {input_content}")

    response = client.chat.completions.create(
        model="glm-4-flash",
        messages=[
            {"role": "user", "content": input_content}
        ],
    )

    # 获取 AI 返回的原始内容
    comment_and_suggestion = response.choices[0].message.content

    # 去除多余内容，提取有效的 JSON 部分
    start_index = comment_and_suggestion.find('{')
    end_index = comment_and_suggestion.rfind('}')
    if start_index != -1 and end_index != -1:
        json_str = comment_and_suggestion[start_index:end_index + 1]
        print(json_str)
        try:
            # 解析 JSON 格式的 AI 回复
            comment_dict = json.loads(json_str)
            return comment_dict
        except json.JSONDecodeError as e:
            print(f"JSON 解析错误: {e}")
            return {"error": "JSON 解析错误，请检查 AI 返回内容"}
    else:
        return {"error": "未找到有效的 JSON 数据，请检查 AI 返回内容"}
